package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.loveto.common.ImageDownloader;
import com.loveto.common.JsonUtils;
import com.loveto.constant.LovetoConstant;

public class MessageFriendActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private ProgressDialog progressDialog;
	private LinearLayout contentMain;
	private String memberID;
	private String local;
	private String local_detail;
	private String gender;
	private String age;
	private String messageMemberSeq;
	private String friendId;
	private Handler myHandler = new Handler();
	private RelativeLayout talkLayout;
	private LinearLayout contentMainInner;
	
	private boolean isFinish = false;
	private String messageid;
	
	private String phone_uid;
	private String errorMsg;
	private String suspend_date;
	private String suspend_reason;
	private boolean isSendSuccess = false;
	
	private ScrollView mScroll;
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_message_friend);
		((RelativeLayout)findViewById(R.id.btn_goto_back)).setOnClickListener(this);
		contentMain = (LinearLayout)findViewById(R.id.content_main);
		
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberID = pref.getString("memberid", "");
		phone_uid = pref.getString("phone_uid", "");
		local = pref.getString("local", "");
		local_detail = pref.getString("local_detail", "");
		gender = pref.getString("gender", "");
		age = pref.getString("age", "");

		progressDialog = new ProgressDialog(MessageFriendActivity.this);
		progressDialog.setMessage("정보를 불러오고있습니다.");
		progressDialog.show();
		init();
		
		mScroll = (ScrollView) findViewById(R.id.message_scroll);
		
		//클릭 리스너 달기
		((TextView)findViewById(R.id.btn_send)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.btn_report_message)).setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_goto_back:
				isFinish = true;
//				Intent intentMoveToPage = new Intent(MessageFriendActivity.this,
//						MessageMainActivity.class);
//				startActivity(intentMoveToPage);
				finish();
				break;
			case R.id.btn_report_message:
				showAlertReport();
				break;
			case R.id.btn_send:
				if (isNetworkAvailableAndNotice()) {
					sendTalkMessage();
				}
				break;
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		isFinish = true;
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		getTalkListPeriodic();
	}
	
	/*
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

	    switch (ev.getAction()){
	        case MotionEvent.ACTION_DOWN:
	        	EditText messageToSend = (EditText) findViewById(R.id.talk_message_to_send);
	        	InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	        	mgr.hideSoftInputFromWindow(messageToSend.getWindowToken(), 0);
	            break;
	        case MotionEvent.ACTION_UP:
	            break;
	    }

	    return super.dispatchTouchEvent(ev);
	}*/
	
	private void sendTalkMessage() {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				Log.d("tag", "sendTalkMessage() start");
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						if ("M".equals(gender)) {
							talkLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_friend_my_talk_man, null);
						} else {
							talkLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_friend_my_talk_woman, null);
						}
						
						EditText messageToSendEditText = (EditText)findViewById(R.id.talk_message_to_send);
						String message = messageToSendEditText.getText().toString();
						if (message.length() == 0) {
							showSimpleAlert("메시지는 1글자 이상 입력해주세요.");
							return;
						} 
						
						TextView talkMessageTextView = (TextView)talkLayout.findViewById(R.id.talk_message);
						talkMessageTextView.setText(message);
						
						TextView regdateTextView = (TextView)talkLayout.findViewById(R.id.regdate);
						regdateTextView.setText( new SimpleDateFormat("yyyy.MM.dd hh:mm").format(new Date()));
						
						ImageDownloader imageDownloader = new ImageDownloader();
						ImageView userPhotoImageView = (ImageView)talkLayout.findViewById(R.id.talk_message_photo);
						String userPhotoUrl = LovetoConstant.PHOTO_THUMB_URL + memberID + ".jpg";
						imageDownloader.download(userPhotoUrl, userPhotoImageView);
						contentMain.addView(talkLayout);
						messageToSendEditText.setText("");
						scrollToBottom();
						
						try {
							StringBuffer url = new StringBuffer(LovetoConstant.MESSAGE_TALK_SAVE_URL);
							url.append("?messagememberseq=").append(messageMemberSeq).append("&messagecontent=").append(URLEncoder.encode(message, "UTF-8"));
							url.append("&receiver_memberid=").append(friendId).append("&sender_memberid=").append(memberID).append("&phone_uid=").append(phone_uid);
							String urlStr = url.toString();
							Log.d("tag", "urlStr : " + urlStr);
							String jsonText = JsonUtils.getStringFromUrl(urlStr);
							Log.d("tag", "jsonText :" + jsonText);
							JSONObject jsonObject = new JSONObject(jsonText);
							String result = jsonObject.getString("result");
							Log.d("tag", "result : "  + result);
							String err = jsonObject.getString("err");
							Log.d("tag", "err : "  + err);
							suspend_date = jsonObject.getString("suspend_date");
							Log.d("tag", "suspend_date : "  + suspend_date);
							suspend_reason = jsonObject.getString("suspend_reason");
							Log.d("tag", "suspend_reason : "  + suspend_reason);
							if (result.equals("F")) {
								Log.d("tag", "err : "  + err);
								errorMsg = err;
								isSendSuccess = false;
								//int lastChildIndex = contentMain.getChildCount() - 1;
								//contentMain.getChildAt(lastChildIndex);
								((TextView)talkLayout.findViewById(R.id.talk_message)).setTextColor(Color.RED);
							} else {
								isSendSuccess = true;
								messageid = result;
								Log.d("tag", "messageid : "  + messageid);
								Log.d("tag", "err :  : "  + err);
							}
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							if (!isSendSuccess && "Incorrect PhoneID".equals(errorMsg)){
								//폰 인증정보가 틀린 경우
								showAlertIncorrectPhoneID(MessageFriendActivity.this);
							} else if (!isSendSuccess && "SuspendedID".equals(errorMsg)) {
								//이용 정지 상태인 경우
								showAlertSuspendID(MessageFriendActivity.this, suspend_date, suspend_reason);
							} else if (!isSendSuccess) {
								showSimpleAlert("쪽지 전송에 실패했습니다. 다시 시도해주세요!");
							}
						}
					}
				});
				Log.d("tag", "sendTalkMessage() end");
			}
		};
		new Thread(runnable).start();
	}
	
	private void makeProfileArea() {
		// 프로필 영역
		// 사용자
		// 유저 인포 텍스트 변경
		StringBuffer sb = new StringBuffer();
		sb.append(memberID);
		sb.append(", ");
		sb.append(local);
		if ( (!local_detail.equals("")) && (!local_detail.equals("null"))) {
			sb.append(" ");
			sb.append(local_detail);
		}
		sb.append(", ");
		sb.append(age);
		TextView userInfoTextView = (TextView)findViewById(R.id.message_profile_user_info);
		userInfoTextView.setText(sb);
		Log.d("tag","userInfo : " + sb);
		
		//사진 변경
		ImageDownloader imageDownloader = new ImageDownloader();
		ImageView userPhotoImageView = (ImageView)findViewById(R.id.message_profile_user_photo);
		String userPhotoUrl = LovetoConstant.PHOTO_THUMB_URL + memberID + ".jpg";
		imageDownloader.download(userPhotoUrl, userPhotoImageView);
		
		
		// 상대방
		//전 엑티비티에서 친구정보 받아오기
		Intent intent = getIntent();
		String friendInfo = intent.getStringExtra("friendInfo");
		Log.d("tag","friendInfo : " + friendInfo);
		TextView friendInfoTextView = (TextView)findViewById(R.id.message_profile_friend_info);
		friendInfoTextView.setText(friendInfo);
		
		//사진 변경
		ImageView friendPhotoImageView = (ImageView)findViewById(R.id.message_profile_friend_photo);
		friendId = friendInfo.trim().split(",")[0];
		Log.d("tag","friendId : " + friendId);
		String friendPhotoUrl = LovetoConstant.PHOTO_THUMB_URL + friendId + ".jpg";
		imageDownloader.download(friendPhotoUrl, friendPhotoImageView);
		
		// 타이틀 바 변경
		TextView talkTitleTextView = (TextView)findViewById(R.id.talkTitle);
		talkTitleTextView.setText(friendId);
	}
	
	private void init() {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				Log.d("tag", "setTalkList() start");
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						makeProfileArea();
					}
				});
				Intent intent = getIntent();
				messageMemberSeq = intent.getStringExtra("messageMemberSeq");
				
				getTalkListPeriodic();
			}
		};
		
		new Thread(runnable).start();
	}
	
	private void getTalkListPeriodic() {
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				Log.d("tag", "setTalkList() start");
				while(!isFinish) {
					getTalkList();
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						viewToast(Gravity.CENTER, 0, 0, "getTalkListPeriodic() 실행 중 오류 발생!");
						e.printStackTrace();
					}
				}
			}
		};
		
		new Thread(runnable).start();
	}

	private void getTalkList() {
		StringBuffer url = new StringBuffer(LovetoConstant.MESSAGE_TALK_LIST_URL);
		url.append("?messagememberseq=").append(messageMemberSeq);
		url.append("&memberid=").append(memberID);
		
		if (messageid != null) {
			url.append("&messageid=").append(messageid);
		} else {
			url.append("&messageid=").append(0);
		}
		
		contentMainInner = new LinearLayout(MessageFriendActivity.this);
		contentMainInner.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		contentMainInner.setOrientation(LinearLayout.VERTICAL);
		
		try {
			String jsonText = JsonUtils.getStringFromUrl(url.toString());
			Log.d("tag", jsonText);
			JSONArray jsonArray;
			jsonArray = new JSONArray(jsonText);
			final int jsonArrayLen = jsonArray.length();
			
			for (int i = 0; i < jsonArrayLen; i++) {
				final JSONObject object = jsonArray.getJSONObject(i);
				
				myHandler.post(new Runnable() {
					@Override
					public void run() {
						
						String sendermemberid;
						String receivermemberid;
						String messagecontent;
						String readyn;
						String regdt;
						try {
							sendermemberid = object.getString("sender_memberid");
							receivermemberid = object.getString("receiver_memberid");
							messagecontent = object.getString("messagecontent");
							readyn = object.getString("read_yn");
							regdt = object.getString("regdate");
							messageid = object.getString("messageid");
						
							if (memberID.equals(sendermemberid)) {
								if ("M".equals(gender)) {
									talkLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_friend_my_talk_man, null);
								} else {
									talkLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_friend_my_talk_woman, null);
								}
							} else {
								if ("M".equals(gender)) {
									talkLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_friend_other_talk_woman, null);
								} else {
									talkLayout = (RelativeLayout)getLayoutInflater().inflate(R.layout.loveto_message_friend_other_talk_man, null);
								}
							}
							
							TextView talkMessageTextView = (TextView)talkLayout.findViewById(R.id.talk_message);
							talkMessageTextView.setText(messagecontent);
							
							TextView regdateTextView = (TextView)talkLayout.findViewById(R.id.regdate);
							regdateTextView.setText(regdt);
							
							//사진 변경
							ImageDownloader imageDownloader = new ImageDownloader();
							ImageView userPhotoImageView = (ImageView)talkLayout.findViewById(R.id.talk_message_photo);
							String userPhotoUrl = LovetoConstant.PHOTO_THUMB_URL + sendermemberid + ".jpg";
							imageDownloader.download(userPhotoUrl, userPhotoImageView);
							contentMainInner.addView(talkLayout);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
			}
		
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {
			myHandler.post(new Runnable() {
				@Override
				public void run() {
					contentMain.addView(contentMainInner);
					Log.d("tag", "스크롤 바닥으로 이동");
					scrollToBottom();
					progressDialog.dismiss();
				}
			});
			Log.d("tag", "setTalkList() end");
		}
	}
	
	private void scrollToBottom() {
		
		//이렇게하면 빠르게 적용 된다고함.
		mScroll.post(new Runnable() {
			@Override
			public void run() {
				mScroll.fullScroll(ScrollView.FOCUS_DOWN);
			}
		});
		
	}
	
    private void showAlertReport() {
		new AlertDialog.Builder(this)
		.setTitle("신고")
		.setMessage("욕설/홍보/음란성/허위정보 등을 신고해주세요! 단,허위신고는 불이익을 받을 수 있습니다.")
		.setPositiveButton("신고", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				Intent intent = new Intent(MessageFriendActivity.this,ReportUserActivity.class);
				intent.putExtra("category", "message");
				intent.putExtra("target_userID", friendId);
				intent.putExtra("tournamentID", 0);
				startActivity(intent);
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		})
		.show();
    }
}
